package app.base.systemmanage.systemmodulesmanage;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;

import app.base.common.FileOperation;
import app.base.common.Utility;

import app.base.systemmanage.systemmodulesmanage.dao.SysModulesDAO;
import app.base.systemmanage.systemmodulesmanage.model.SysModules;

public class SystemModulesHandle extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
			
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 
				
		//这里验证客户端会话是否已过期
		
		String cmd = request.getParameter("SYS_OP_CMD").trim();
		String result = null;

		if (cmd == null)
		{
			result = "{returnCode: '-1', msg: '客户端的数据请求命令参数CMD为NULL'}";
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_ADD) || cmd.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
		{
			SysModules record = new SysModules();
						
			record.setMOD_ID(URLDecoder.decode(request.getParameter("MOD_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMOD_PARENT_ID(URLDecoder.decode(request.getParameter("MOD_PARENT_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMOD_NAME(URLDecoder.decode(request.getParameter("MOD_NAME").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMOD_DESC(URLDecoder.decode(request.getParameter("MOD_DESC").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setMOD_CFG_PATH(URLDecoder.decode(request.getParameter("MOD_CFG_PATH").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setNORMAL_IMG_URL(URLDecoder.decode(request.getParameter("NORMAL_IMG_URL").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setEXPAND_IMG_URL(URLDecoder.decode(request.getParameter("EXPAND_IMG_URL").trim(), Utility.CHARSET_ENCODING_UTF8));
			record.setLEAF_NODE_FLAG(request.getParameter("LEAF_NODE_FLAG").trim());
			record.setDISPLAY_RANKING_INDEX(BigDecimal.valueOf(Long.valueOf(request.getParameter("DISPLAY_RANK_INDEX").trim())));
			record.setSYS_HOLD_FLAG(request.getParameter("SYS_HOLD_FLAG").trim());

			result = doSystemOperations(cmd, record);
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("MOD_ID", URLDecoder.decode(request.getParameter("MOD_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			
			result = doSystemOperations(cmd, map);
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_GENERATE))
		{
			result = doSystemOperations(cmd, null);
		}
		else
		{
			result = "{returnCode: '-1', msg: '服务器不支持的数据请求命令，请检查后再重试'}";
		}
		
		out.println(result);
		
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
		doGet(request, response);
	}
	
	@SuppressWarnings("unchecked")
	private String doSystemOperations(String action, Object o)
	{
		
		String result = "{returnCode: '-1', msg: '系统调用函数 doSystemOperations() 失败'}";
		
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysModulesDAO sysModulesDAO = (SysModulesDAO)context.getBean(Utility.SYSTEM_MODULES_MANAGE_MODULE_BEAN_NAME);
		
		if (action.equals(Utility.SYS_OPERATION_COMMAND_ADD))
		{
			result = insert(sysModulesDAO, (SysModules) o);
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
		{
			result = update(sysModulesDAO, (SysModules) o);
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{			
			result = delete(sysModulesDAO, (Map<String, Object>) o);			
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_GENERATE))
		{			
			result = generate(this.getServletConfig().getServletContext().getRealPath("/") + Utility.APP_SYS_MODULES_CONFIGURATION_INCLUDE_PATH);			
		}
		
		return result;
	}
	
	private String insert(SysModulesDAO sysModulesDAO, SysModules record)
	{
		String result = "{returnCode: '0', msg: '新增系统模块项成功'}";
		
		try {
			sysModulesDAO.insert_0001(record);		
		} 
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许创建重复的模块项'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}

	private String update(SysModulesDAO sysModulesDAO, SysModules record)
	{
		String result = "{returnCode: '0', msg: '修改系统模块项成功'}";
		
		try {
			sysModulesDAO.update_0001(record);		
		} 		
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许在同一模块分类下创建相同名称的多个模块项'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}
	
	private String delete(SysModulesDAO sysModulesDAO, Map<String, Object> map)
	{
		String result = "{returnCode: '0', msg: '删除系统模块项成功'}";
		
		try {
			sysModulesDAO.delete_0001(map);		
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}	
	
	@SuppressWarnings("unchecked")
	public String generate(String fileName)
	{
		String result = "{returnCode: '0', msg: '更新系统模块配置缓存文件成功，请刷新客户端浏览器'}";

		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysModulesDAO sysModulesDAO = (SysModulesDAO)context.getBean(Utility.SYSTEM_MODULES_MANAGE_MODULE_BEAN_NAME);
		
		List<SysModules> list = sysModulesDAO.select_0002();
				
		StringBuffer sb = new StringBuffer("");
		
		int index = 0;
		
		for(; index < list.size(); index++){
			SysModules sysModules = (SysModules) list.get(index);
			
			String moduleName = sysModules.getMOD_NAME().trim();
			String configPath = sysModules.getMOD_CFG_PATH() == null ? "" : sysModules.getMOD_CFG_PATH().trim();
			
			sb.append("<!--" + moduleName + "-->" + Utility.UNIX_TERMINATORS);
			sb.append(configPath + Utility.UNIX_TERMINATORS);
		}
		
		try {
			FileOperation fo = new FileOperation(fileName);
			fo.writeto(sb.toString(), Utility.CHARSET_ENCODING_UTF8, false);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub			

	}

}